<template>
  <a-drawer
    title="过滤权限配置"
    :maskClosable="true"
    placement="right"
    :closable="true"
    width=400
    height="100%"
    @close="close"
    :visible="visible"
  >
    <vxe-grid
      id="RoleDataFilterList"
      ref="vxeTable"
      v-bind="gridOptions"
      :height="height"
      v-on="listeners"
      :pager-config="false"
      :row-config="{keyField:'id'}"
      :toolbarConfig="false"
    >
    </vxe-grid>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="close" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleOk" type="primary" :loading="loading">保存</a-button>
    </div>
  </a-drawer>
</template>

<script>
import { Drawer as ADrawer } from 'ant-design-vue'
import VxeTableListMixin from '@/mixins/VxeTableListMixin'
import { DATA_SCOPE } from '@/store/mutation-types'
import { postAction, getAction } from '@/services/manage'
import { CURY_TYPE } from '@/store/mutation-types'
export default {
  name: 'RoleDataFilterListModal',
  mixins: [VxeTableListMixin],
  components: { ADrawer },
  props: {
    roleId: String
  },
  data() {
    return {
      columns: [
        { type: 'checkbox', width: 40 },
        { type: 'seq', width: 40 },
        { title: '权限范围', field: 'dataScope', slots: { default: ({ row }) => {
          if (row.dataScope === DATA_SCOPE.USER) {
            return '按用户'
          }
          if (row.dataScope === DATA_SCOPE.DEPT) {
            return '按部门'
          }
          if (row.dataScope === DATA_SCOPE.SERVICE) {
            return '按服务'
          }
          if (row.dataScope === DATA_SCOPE.DEPT_AND_CHILD) {
            return '部门及子部门'
          }
          return ''
        } }},
        { title: '描述', field: 'description' }
      ],
      url: {
        list: '/datafilter/res/list/',
        save: '/datafilter/role/add/batch',
        within: '/datafilter/role/within/'
      },
      proxyConfig: {
        autoLoad: false
      },
      visible: false,
      loading: false,
      resData: {},
      defaultCheckedObj: {},
      height: 300
    }
  },
  methods: {
    close() {
      this.$emit('close')
      this.visible = false
    },
    async show(row) {
      this.url.list = `/datafilter/res/list/${row.id}`
      this.resData = row
      this.visible = true
      await this.loadData()
      this.getRoleFilter()
      this.$nextTick(() => {
        this.setTableHeight()
      })
    },
    handleOk() {
      const select = this.$refs.vxeTable.getCheckboxRecords()
      const data = []
      this.checkedKeys = []

      // 遍历选中数据，判断是新增还是编辑
      select.forEach(item => {
        data.push({
          roleId: this.roleId,
          dataFilterId: item.id,
          id: this.defaultCheckedObj[item.id] && this.defaultCheckedObj[item.id].id,
          crudType: this.defaultCheckedObj[item.id] ? CURY_TYPE.UPDATE : CURY_TYPE.SAVE
        })
        this.checkedKeys.push(item.id)
      })

      // 遍历之前原始选中数据，判断是否需要删除
      Object.keys(this.defaultCheckedObj).forEach(key => {
        if (!this.checkedKeys.includes(key)) {
          const item = this.defaultCheckedObj[key]
          data.push({
            roleId: item.roleId,
            crudType: 'DELETE',
            dataFilterId: item.dataFilterId,
            id: item.id
          })
        }
      })
      this.loading = true

      // 执行保存
      postAction(this.url.save, data).then(res => {
        if (res.success) {
          this.$message.success('操作成功')
          this.close()
        }
      }).finally(() => {
        this.loading = false
      })
    },
    setTableHeight() { // 设置页面表格高度
      if (this.$refs.vxeTable) {
        const clientHeight = document.documentElement.clientHeight
        const tableTop = this.$refs.vxeTable.$el.getBoundingClientRect().top
        this.height = clientHeight - tableTop - 150
      }
    },
    getRoleFilter() {
      getAction(`${this.url.within}${this.resData.id}/${this.roleId}`).then(res => {
        if (res.success) {
          this.defaultCheckedObj = {} // 保存初始化选中
          const defaultChecked = []
          res.result.forEach(item => {
            this.defaultCheckedObj[item.dataFilterId] = item
            defaultChecked.push({ id: item.dataFilterId })
          })
          this.$refs.vxeTable.setCheckboxRow(defaultChecked, true)// 初始化选中
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .drawer-bootom-button {
    position: absolute;
    bottom: 0;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }

</style>
